package com.flyco.modules.stm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.flyco.modules.stm.entity.DistributorDistrictEntity;
import com.flyco.modules.stm.entity.DistrictEntity;
import com.flyco.modules.stm.mapper.DistributorDistrictDao;
import com.flyco.modules.stm.mapper.DistrictDao;
import com.flyco.modules.stm.vo.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/f/ss/district", method = RequestMethod.POST)
@Transactional
public class DistributorDistrictController {

    private final DistributorDistrictDao distributorDistrictDao;

    private final DistrictDao districtDao;

    @Autowired
    public DistributorDistrictController(DistributorDistrictDao distributorDistrictDao, DistrictDao districtDao) {
        this.distributorDistrictDao = distributorDistrictDao;
        this.districtDao = districtDao;
    }

    @RequestMapping(path = "/transfer")
    public ResponseInfo transfer() throws Exception {

        Long parentId = 0L;
        List<DistrictEntity> provinceEntities = this.listByParentId(parentId);

        for (DistrictEntity provinceEntity : provinceEntities) {
            this.copyDistrict(provinceEntity);
            List<DistrictEntity> cityEntities = this.listByParentId(provinceEntity.getId());
            for (DistrictEntity cityEntity : cityEntities) {
                this.copyDistrict(cityEntity);
                List<DistrictEntity> districtEntities = this.listByParentId(cityEntity.getId());
                for (DistrictEntity districtEntity : districtEntities) {
                    this.copyDistrict(districtEntity);
                }
            }
        }


        return new ResponseInfo();
    }

    private void copyDistrict(DistrictEntity entity) {
        DistributorDistrictEntity pentity = new DistributorDistrictEntity();
        BeanUtils.copyProperties(entity, pentity);
        this.distributorDistrictDao.insert(pentity);
    }


    private List<DistrictEntity> listByParentId(Long parentId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parentDistrictId", parentId);
        return this.districtDao.selectList(queryWrapper);
    }
}
